using System;
using System.Windows.Forms;

using FreeFlow.Client;

namespace FreeFlow.WinFormsControls
{
	/// <summary>
	/// A dropdown control.
	/// </summary>
	public class DropDownControl : ComboBox, IFillable, IRefillable
	{
    /// <summary>
    /// Creates a new <see cref="DropDownControl"/> instance.
    /// </summary>
		public DropDownControl()
		{
    }

    #region IFillable Members

    /// <summary>
    /// Renders the dropdown control with static layout information using the specified field.
    /// </summary>
    /// <param name="field">Field.</param>
    public void Render(FreeFlow.Client.Field field)
    {
      DropDownStyle = ComboBoxStyle.DropDownList;
    }

    /// <summary>
    /// Fills the dropdown control with values from the specified field.
    /// </summary>
    /// <param name="field">Field.</param>
    public void Fill(FreeFlow.Client.Field field)
    {
      DropDownField dropdownField = (DropDownField)field;

      // disconnect the event handler if it is already attached
      SelectedIndexChanged -= new EventHandler(dropdownControl_SelectedIndexChanged);

      // add items
      Items.Clear();
      for (int optionLoop = 0; optionLoop < dropdownField.OptionCount; optionLoop++)
      {
        Items.Add(dropdownField.Option(optionLoop));
      }

      if (dropdownField.Value != null)
        SelectedIndex = Items.IndexOf(dropdownField.Value);
          
      // connect event handler here so it doesn't trigger a refill aboce
      SelectedIndexChanged += new EventHandler(dropdownControl_SelectedIndexChanged);
    }

    /// <summary>
    /// Fills the field from the control.
    /// </summary>
    /// <param name="field">Field.</param>
    public void FillField(Field field)
    {
      if (field != null)
      {
        if (SelectedItem == null)
          field.Value = "";
        else
          field.Value = SelectedItem.ToString();
      }
    }

    #endregion
    #region IRefillable Members

    /// <summary>
    /// Event triggered when a refill should occur
    /// </summary>
    public event EventHandler Refill;

    #endregion
  
    private void dropdownControl_SelectedIndexChanged(object sender, EventArgs e)
    {
      if (Refill != null)
        Refill(this, e);
    }
  }
}
